<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24" v-show="tab==1">
            <a-form-item label="活动名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['activityName', validatorRules.activityName]" placeholder="请输入活动名称"  ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-show="tab==1">
            <a-form-item label="活动类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radio" v-decorator="['activityType', validatorRules.activityType]" :trigger-change="true" dictCode="activity_type" @change="changeActivityType"/>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-show="tab==1&&model.activityType==1">
            <a-form-item label="最大金额"  :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number :max="100000" :min="0.01" :step="1" :formatter="limitNumber" :parser="limitNumber"  v-decorator="['maxMoney', validatorRules.maxMoney]" placeholder="请输入最大金额" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24" v-show="tab==1&&model.activityType==1">
            <a-form-item label="最小金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number  :max="100000" :min="0.01" :step="1" :formatter="limitNumber" :parser="limitNumber" v-decorator="['minMoney', validatorRules.minMoney]"  placeholder="请输入最小金额" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24" v-show="tab==1&&model.activityType==2">
            <a-form-item label="单个金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number  :max="100000" :min="0.01" :step="1" :formatter="limitNumber" :parser="limitNumber" v-decorator="['singleMoney', validatorRules.singleMoney]" placeholder="请输入单个金额" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24" v-show="tab==1&&model.activityType==2">
            <a-form-item label="红包个数" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number :step="1"  :max="1000000" v-decorator="['num', validatorRules.num]" placeholder="请输入红包个数" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24" v-show="tab==1">
            <a-form-item label="门槛" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number :max="100000" :min="0.01" :step="1" :formatter="limitNumber" :parser="limitNumber" v-decorator="['threshold', validatorRules.threshold]" placeholder="请输入门槛" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="24" v-show="tab==2">
            <a-form-item label="微信二维码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <span style="color: #ff0000">(图片大小：＜1M)</span>
              <j-image-upload bizPath="marketing/wxCode" isMultiple  v-decorator="['wxCode',validatorRules.wxCode]" ></j-image-upload>
            </a-form-item>
          </a-col>
          <!--        <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                    <a-button @click="submitForm">提 交</a-button>
                  </a-col>-->
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue,moneyFormat } from '@/utils/util'

  export default {
    name: 'QyMarketingForm',
    components: {
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          activityName: {
            rules: [
              { required: true, message: '请输入活动名称!'},
            ]
          },
          maxMoney: {
            rules: [
              { required: true, message: '请输入最大金额!'}
            ]
          },
          minMoney: {
            rules: [
              { required: true, message: '请输入最小金额!'},
              {validator:this.checkMax}
            ]
          },
          singleMoney: {
            rules: [
              { required: true, message: '请输入单个金额!'}
            ]
          },
          num:{
            rules: [
              { required: true, message: '请输入红包个数!'},
              { pattern: /^-?\d+$/, message: '请输入整数!'},
            ]
          },
          threshold: {
            rules: [
              { required: true, message: '请输入门槛!'},
              {validator:this.checkMenKan}
            ]
          },
          wxCode: {
            rules: [
              { required: true, message: '请上传微信二维码!'},
            ]
          },
        },
        url: {
          add: "/qy/qyMarketing/add",
          edit: "/qy/qyMarketing/edit",
          queryById: "/qy/qyMarketing/queryById"
        },tab:1
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      add() {
        this.edit({});
      },
      edit(record) {
        if (!record.activityType) {
          record.activityType = 1;
        }

        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.model = this.formatFormData(this.model,1);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'activityName', 'activityType', 'maxMoney', 'minMoney', 'singleMoney', 'num', 'threshold', 'joinPerson', 'useNum', 'wxCode'))
        })
      },
      //渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = {id: this.formData.dataId};
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm() {
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err||(err && !err.wxCode)) {
            if (values.activityType == 1) {
              values.singleMoney = '';
              values.num = '';
            } else {
              values.maxMoney = '';
              values.minMoney = '';
            }
            this.toSumbit(values);
            if (this.model.activityType == 1) {
              this.model.singleMoney = '';
              this.model.num = '';
            } else {
              this.model.maxMoney = '';
              this.model.minMoney = '';
            }

          }

        })
      }, toSumbit(values) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        let formData = Object.assign(this.model, values);
        formData =  this.formatFormData(formData);
        console.log("表单提交数据", formData)
        httpAction(httpurl, formData, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.$emit('ok');
            this.tab = 1;
          } else {
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
        })
      },formatFormData(formData,type){
        if(formData.maxMoney){
          formData.maxMoney = moneyFormat(formData.maxMoney,type);
        }
        if(formData.minMoney){
          formData.minMoney = moneyFormat(formData.minMoney,type);
        }
        if(formData.singleMoney){
          formData.singleMoney = moneyFormat(formData.singleMoney,type);
        }
        if(formData.threshold){
          formData.threshold = moneyFormat(formData.threshold,type);
        }
        return formData;
      }
      ,
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'activityName', 'activityType', 'maxMoney', 'minMoney', 'singleMoney', 'num', 'threshold', 'joinPerson', 'useNum', 'wxCode'))
      }, changeActivityType() {
        if (this.model.activityType == 1) {
          this.model.activityType = 2;
        } else {
          this.model.activityType = 1;
        }

      }, toNext() {

        this.form.validateFields((err, values) => {
          if (!err) {
            this.tab = 2;
            this.$emit("switchTab", 2);
          } else {
            if (!err.activityName && !err.threshold) {
              if (this.model.activityType == 1) {
                if (!err.maxMoney && !err.minMoney) {
                    this.tab = 2;
                    this.$emit("switchTab", 2);
                    values.singleMoney = '';
                    values.num = '';
                }
              } else {
                if (!err.singleMoney && !err.num) {
                  this.tab = 2;
                  this.$emit("switchTab", 2);
                  values.maxMoney = '';
                  values.minMoney = '';
                }
              }
            }

          }
        });
      }, toTab1() {
        this.tab = 1;
      }, limitNumber(value) {
        value = value + '';
        value = value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
        value = value.replace(/^\./g,""); //验证第一个字符是数字
        value = value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
        value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
        if(value.indexOf(".")< 0 && value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          value= parseFloat(value);
        }
        return value;
      },checkMax(rule, value, callback){
        const form = this.form;
        console.log(form);
        if(value>form.getFieldValue('maxMoney')){
          callback('最小金额不能大于最大金额！');
        }else{
          callback();
        }
      },checkMenKan(rule, value, callback){
        const form = this.form;
        if(this.model.activityType==1){
          if(value<form.getFieldValue('maxMoney')){
            callback('门槛不能低于最大金额！');
          }else{
            callback();
          }
        }else{
          if(value<form.getFieldValue('singleMoney')){
            callback('门槛不能低于单个金额！');
          }else{
            callback();
          }
        }

      }
    }
  }
</script>